package com.mxpio.erp.purchase.provider;

import com.mxpio.erp.common.enums.OrderStatusEnums;
import com.mxpio.erp.common.purchase.entity.PurchaseOrder;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.query.Criterion;
import com.mxpioframework.jpa.query.Operator;
import com.mxpioframework.jpa.query.SimpleCriterion;
import com.mxpioframework.security.access.datascope.provider.DataScapeProvider;
import com.mxpioframework.security.util.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author : wpp
 * @Datetime : 2023/4/19 14:25
 * @Desc :
 * @Modor :  Modifytime:
 * @modDesc : 采购订单明细，根据主表中的业务员来过滤
 */
@Component
public class CurrentBizManForPurchaseDetailProvider implements DataScapeProvider {
    @Override
    @Transactional
    public List<Criterion> provide() {
        String loginUsername = SecurityUtils.getLoginUsername();
        List<Criterion> appendCriterions = new ArrayList<>();
        if (StringUtils.isBlank(loginUsername)){
            appendCriterions.add(new SimpleCriterion("createTime", Operator.EQ,new Date(0)));//如果未匹配到过滤条件，则增加一个不能正常匹配到数据的条件
            return appendCriterions;
        }
        //思路，查询到符合条件的采购单bizNo
        List<PurchaseOrder> purchaseOrderList = JpaUtil.linq(PurchaseOrder.class).equal("bizMan", loginUsername)
                .notEqual("closeStatus", OrderStatusEnums.CloseStatus.CLOSED.getStatusCode())
                .equal("bpmnStatus", OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode())
                .notEqual("orderStatus", OrderStatusEnums.OrderStatus.CLEARED.getStatusCode()).list();
        if (purchaseOrderList.size()>0){
            Set<String> bizNoSet = purchaseOrderList.stream().map(PurchaseOrder::getBizNo).collect(Collectors.toSet());
            appendCriterions.add(new SimpleCriterion("bizNo", Operator.IN,bizNoSet));
        }else{
            appendCriterions.add(new SimpleCriterion("createTime", Operator.EQ,new Date(0)));//如果未匹配到过滤条件，则增加一个不能正常匹配到数据的条件
        }
        return appendCriterions;
    }
}
